package data;


import java.util.List;

import models.*;

import org.sql2o.Sql2o;

public class AuthDAO implements IAuthDAO{
	private static Sql2o database;
	static {
		database = new Connection().open();
	}
	
	public User authenticate(String username, String password){
		String sql = "select id, username, personId from User where username = :username and password = :password Limit 1";
		// find user
		User user = database.createQuery(sql)
							.addParameter("username", username)
							.addParameter("password", password)
							.executeAndFetchFirst(User.class);
		// get roles
		if(user != null) {
			sql = "select * from Role where id In (select roleId from UserInRole where userId = :userId)";
			List<Role> roles = database.createQuery(sql).addParameter("userId", user.getId()).executeAndFetch(Role.class);
			user.setRoles(roles);
		}
		return user;
	}
	
}
